/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pk.ecompuefs.micc.dfs.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import pk.ecompuefs.micc.dfs.master.Master;
import pk.ecompuefs.micc.dfs.util.User;

/**
 *
 * @author emanuel
 */
public class Client {
    
    private Socket client;
    private Socket slave;
    private String masterIP;    
    private ObjectOutputStream oos;
    private ObjectInputStream ois;
    private User user;
    public int acknoledge;
    private  List<String> slaves;
    
    public Client() {
        
    }
    
    public Socket connect(String HOST, int PORT) {
        try {
            
            Socket socket = new Socket(HOST,PORT);            
            return socket;
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
        
    }
    
    public void start() {
        
        while (masterIP == null || masterIP.equals("")) {

                masterIP = JOptionPane.showInputDialog(
                        "Digite o Endereço do Servidor Master");
                System.out.println(masterIP);
                
                client = connect(masterIP, 4011);
           
            
                if (masterIP == null || masterIP.equals("")) {

                    JOptionPane.showMessageDialog(null,
                            "Você não digitou um endereço válido.");
                }
        }        
    }
    
    public void running(){
        int code;
        boolean answer = true;
        while(answer){
            try {
                DataInputStream input = new DataInputStream(client.getInputStream());
                code = input.readInt();
                System.out.println(code);
                
                switch(code){
                        
                    case 13:
                        setAcknoledge(13);
                 //       JOptionPane.showMessageDialog(null, "Connected to the FTP Server "
                   //                                     + getHOST(), "Client Runing", 1);
                        receiveSlavesList();
                        connect(slaves.get(0).substring(1), 4012);
                        answer = false;
                    break;
            
                    case 14:
                        setAcknoledge(14);
                        JOptionPane.showMessageDialog(null, "Senha Errada "
                                                        , "Client Runing", 1);                 
                        answer = false;
                    break;
                    
                    case 15:
                        setAcknoledge(15);
                        JOptionPane.showMessageDialog(null, "Email não Cadastrado em "
                                                        + masterIP, "Client Runing", 1);
                        answer = false;                        
                    break;
                                      
                    default:
                        System.out.println("Comando não Identificado..");
                        answer = false;
           
                }
            } catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
        }        
    }
    
    public void sendUser() {
        try {
            
            oos = new ObjectOutputStream(client.getOutputStream());
            oos.writeObject(getUser());
            oos.flush();      
            
            
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public void receiveSlavesList() {
        try {
            ois = new ObjectInputStream(client.getInputStream());
            slaves = (List<String>) ois.readObject();
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return the user
     */
    public User getUser() {
        return user;
    }

    /**
     * @param user the user to set
     */
    public void setUser(User user) {
        this.user = user;
    }
    
    /**
     * Método Utilizado para enviar códigos de Resposta ao Cliente
     * @param code 
     */

    public void sender(int code) {
        DataOutputStream output;
        try {
            output = new DataOutputStream(client.getOutputStream());
            output.writeInt(code);
            output.flush();
        } catch (IOException ex) {
            Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    public int receiver () {
        int code = -1;
            DataInputStream input;
        try {
            input = new DataInputStream(client.getInputStream());
            code = input.readInt();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        return code;
    }
    
    public String getMasterIP(){
        return masterIP;
    }
    
    public void Login() {
        try {
            
            DataOutputStream output = new DataOutputStream(client.getOutputStream());
            output.writeInt(12);
            ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
            oos.writeObject(getUser());            
            oos.flush();
            
            output.flush();
            
           
            // sendFile();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

    }
    
    public void stop() {
        try {
            DataOutputStream output = new DataOutputStream(client.getOutputStream());
            output.writeInt(10);
            output.flush();
            
            client.close();
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
    
    public void register(User user) {        
        
        try {
            DataOutputStream output = new DataOutputStream(client.getOutputStream());
            output.writeInt(16);
            ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
            oos.writeObject(user);
            oos.flush();
            output.flush();
            
                int code;
                boolean answer = true;
                    while(answer){
                        try {
                            DataInputStream input = new DataInputStream(client.getInputStream());
                            code = input.readInt();
                         //   System.out.println(code);
                
                                if(code == 17){
                                    System.out.println("Entrou");
                                    JOptionPane.showMessageDialog(null, "Registration Sucessfull "
                                    + masterIP, "Client Registration", 1);
                                    answer = false;
                                }
            
                                    else if(code == 18){
                                        JOptionPane.showMessageDialog(null, "E-mail Already Exists. Enter a Different E-mail "
                                        , "Client Registration", 1);
                                    answer = false;
                                    }
            
                                        else {
                                            JOptionPane.showMessageDialog(null, "Email não Cadastrado em "
                                            + masterIP, "Client Runing", 1);
                                            answer = false;
                                        }
                            } catch (IOException ex) {
                                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                                }
                        }        
                            } catch (IOException ex) {
                                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                                }      
    }
    
    /**
     * @return the acknoledge
     */
    public int getAcknoledge() {
        return acknoledge;
    }

    /**
     * @param acknoledge the acknoledge to set
     */
    public void setAcknoledge(int acknoledge) {
        this.acknoledge = acknoledge;
    }
    
}
